package com.cloud.rou.im.core.id;

import lombok.Data;

import java.math.BigInteger;
import java.util.Base64;
import java.util.Stack;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 */
public class IdFactory {

    public final static int MAX_SEQ = 0xFFF;
    private static int currentSeq = 0;
    private static final String C_CODES_STRING = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";

    // 时间戳42 自旋ID 12 会话类型4 会话id 22
    public static void main(String[] args) {
       /* for (int i = 0; i < 1000; i++) {
            System.out.println(encode());
        }*/
       HL hl = getHigh();
        System.out.println(ConversionAlphaNumericUtil.encode(hl.getHigh()));
        System.out.println(ConversionAlphaNumericUtil.encode(System.currentTimeMillis()));
        System.out.println(ConversionAlphaNumericUtil.encode(63L));

    }

    private static HL getHigh() {
        Long high = System.currentTimeMillis();
        int spinId = getSpinId();
        high = high << 12;
        high = high | spinId;
        high = high << 4;
        high = high | (12 & 0xF);
        int session = 4194201 & 0x3FFFFF;
        high = high << 6;
        high = high | (session >> 16);
        int low = session & 0xFFFF;
        HL hl = new HL();
        hl.setHigh(high);
        hl.setLow(low);
        return hl;
    }

    @Data
    static class HL {
        private Long high;
        private Integer low;
    }

    /*   private static String encode() {


           String x1 = Integer.toBinaryString(low);
           if(x.length()==64){
               x =  x + x1;
           }else {
               x = "0"+ x + x1;
           }
           StringBuilder re = new StringBuilder();
           for (int i = 0; i < 16; i++) {
               String substring = x.substring(5 * (i), 5 * i + 5);
               char c = C_CODES_STRING.charAt(Integer.parseInt(substring, 2));
               if (i % 4 == 0 && i != 0) {
                   re.append("-").append(c);
               } else {
                   re.append(c);
               }
           }
           return re.toString();
       }*/
    private static String decode(String str) {
        String[] split = str.split("-");
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            String s1 = new BigInteger(s, 10).toString(32);
            System.out.println(s1);
        }
        return null;
    }

    private synchronized static int getSpinId() {
        int seq = currentSeq++;
        if (seq > MAX_SEQ) {
            currentSeq = 0;
            seq = currentSeq++;
        }
        return seq;
    }


}
